<template>
  <div class="hello" id="container">
    <el-row>
      <el-col :span="8">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-upload
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :before-upload="readFile"
            >
              <el-button type="primary">上传配置文件</el-button>
            </el-upload>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" @click="downloadJson">下载配置文件</el-button>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" @click="configDevice">设备配置</el-button>
          </el-col>
          <el-col :span="8">
            <el-switch
              v-model="dragFlag"
              active-text="拖拽"
              inactive-text="连线">
            </el-switch>
          </el-col>
        </el-row>
        <el-row>
          <ul>
            <li id="routeLi">
              <img src="static/router.png" width="70"  @dragend="dragImage($event,1)">
            </li>
            <li>
              <img src="static/switch.png" width="70"  @dragend="dragImage($event,2)">
            </li>
            <li>
              <img src="static/PC.png" width="70" @dragend="dragImage($event,3)">
            </li>
          </ul>
        </el-row>
      </el-col>
      <el-col :span="16">
        <div id="canvasDiv">
          <canvas id="canvas" @dragover.prevent @drop="drop"  width="1000px" height="500px"></canvas>
        </div>
      </el-col>
    </el-row>
    <el-drawer
      title="设备配置"
      :visible.sync="drawer"
      direction="rtl">
      <div>
        <div>
          <el-form label-width="80px" v-model="selectedNode">
            <el-form-item label="名称">
              <el-input v-model="selectedNode.text"></el-input>
            </el-form-item>
            <el-form-item label="TelnetIp">
              <el-input v-model="selectedNode.additionalVal.telnetIp"></el-input>
            </el-form-item>
            <template v-for="item in selectedNode.additionalVal.ports">
              <el-form-item :label="item.port">
                <el-input v-model="item.port" placeholder="请输入端口"></el-input>
              </el-form-item>
              <el-form-item :label="item.port+':ip'">
                <el-input v-model="item.ip" placeholder="请输入ip"></el-input>
              </el-form-item>
              <el-form-item :label="item.port+':掩码'">
                <el-input v-model="item.mask" placeholder="掩码"></el-input>
              </el-form-item>
            </template>
          </el-form>
        </div>
        <div class="demo-drawer__footer">
          <el-button @click="addPort">增加端口</el-button>
          <el-button type="primary" @click="managePort">修改配置</el-button>
        </div>
      </div>

    </el-drawer>
    <el-dialog :destroy-on-close="true" title="shell" :visible.sync="shellDialog" @close="closeShell">
      <el-input
        type="textarea"
        :rows="20"
        disabled
        placeholder=""
        @input="inputResult"
        ref="textarea"
        v-model="result">
      </el-input>
      <el-input
        type="text"
        @keydown.enter.native="commit"
        v-model="command">
        <template slot="prepend">{{prefix}}</template>
      </el-input>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      drawer: false,
      dragFlag: true,
      stage: null,
      scene: null,
      selectedNode: {additionalVal: {}, ports:[]},
      nodeList: [],
      newNode: null,
      shellDialog:false,
      result:'',
      command:'',
      prefix:'root>',
      autoRunFlag: false,
      autoRunIndex: 0,
      autoRunCommand:[],
      websocketPath: 'ws://127.0.0.1:9999/command'
    }
  },
  mounted() {
    // this.initCanvas()
    let canvas = document.getElementById("canvas");
    let stage = new JTopo.Stage(canvas);
    this.scene = new JTopo.Scene(stage);
    this.stage = stage;
    this.scene.background = '/static/img.png';
    let appleNode = new JTopo.Node()
    appleNode.setLocation(0,0)
    appleNode.setSize(80,80)
    appleNode.setImage("static/router.png",true)
    appleNode.setImage("static/PC.png",true)
    appleNode.setImage("static/switch.png",true)
    this.webSocketInit()
    // this.scene.add(appleNode);

  },
  methods: {
    addPort(){
      // console.log(this.selectedNode);
      this.selectedNode.additionalVal.ports.push({ip:"",port:"",mask:''})
    },
    configDevice(){
      this.shellDialog = true
      this.send(`login:${this.selectedNode.additionalVal.telnetIp}`)
    },
    click(event) {
      this.selectedNode = event.target
      this.msg = event.target.text
      // console.log(this.msg);
      if(this.dragFlag){
        return;
      }
      let node = event.target;
      if (node.elementType == 'node') {
        if (this.nodeList[0] != null && node.x == this.nodeList[0].x && node.y == this.nodeList[0].y) {
          return
        }
        this.nodeList.push(node)
      }
    },
    dbclick(event){
      this.drawer = true
      this.selectedNode = event.target

    },
    readFile(file) {

      let reader = new FileReader();
      let that = this;
      this.scene = null;
      reader.readAsText(file)
      // reader.onload = function () {
      //   that.initCanvas()
      //   let canvas = document.getElementById("canvas");
      //   let json = this.result
      //   // let stage = new JTopo.Stage(canvas);
      //
      //   that.stage = new JTopo.createStageFromJson(json, canvas);
      //   that.stage.childs[0].childs.forEach(e => {
      //     e.click(event => that.click(event))
      //     e.dbclick(event => that.dbclick(event))
      //   })
      //   that.stage.centerAndZoom();
      //
      // }
      let type = file.name.split(".")[1]
      // console.log(type);
      reader.onload = function (){
        console.log('success')
        if(type == 'json'){
          that.analyseTopo(this.result)
        } else {
          that.autoRunFlag = true;
          that.analyseCommand(this.result)
        }
      }
    },
    analyseTopo(topo){
      this.initCanvas()
      let canvas = document.getElementById("canvas");
      // let stage = new JTopo.Stage(canvas);

      this.stage = new JTopo.createStageFromJson(topo, canvas);
      this.stage.childs[0].childs.forEach(e => {
        e.click(event => this.click(event))
        e.dbclick(event => this.dbclick(event))
      })
      this.stage.centerAndZoom();

    },
    analyseCommand(command){
      this.autoRunCommand = command.split('\r\n');
      this.autoRunIndex=0
      this.send(this.autoRunCommand[this.autoRunIndex])
      this.autoRunIndex++;
      this.shellDialog = true
    },
    initCanvas(){
      let canvasDiv = document.getElementById('canvasDiv');
      let canvas = document.getElementById("canvas");
      canvasDiv.removeChild(canvas);
      canvas = document.createElement('canvas');
      canvas.width = 1000;
      canvas.height = 500;
      canvas.addEventListener('drop',this.drop)
      canvas.addEventListener('dragover',event => event.preventDefault())
      canvas.id = 'canvas'
      canvasDiv.append(canvas)

    },
    downloadJson(){
      // console.log(this.stage)
      let res = this.stage.toJson();
      // console.log(res);
      let blob = new Blob([res]);
      let downloadElement = document.createElement('a');
      let href = window.URL.createObjectURL(blob); //创建下载的链接
      downloadElement.href = href;
      downloadElement.download = 'diagram.json'; //下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); //点击下载
      document.body.removeChild(downloadElement); //下载完成移除元素
      window.URL.revokeObjectURL(href); //释放blob对象
    },
    createNode(event, x, y){
      let node = new JTopo.Node();
      let img = '';
      switch (event) {
        case 1: img = 'static/router.png';break;
        case 2: img = 'static/switch.png';break;
        case 3: img = 'static/PC.png';break;
        default: return null;
      }
      node.setImage(img, true);
      node.click(this.click)
      node.dbclick(this.dbclick)
      node.setSize(80,80)
      node.additionalVal={ports: []}
      node.text = img
      if(this.scene == null){
        this.scene = this.stage.childs[0]
      }

      node.setLocation(x - 50 - this.scene.translateX,y-40-this.scene.translateY)
      this.scene.add(node);
      return node;
    },
    dragImage(event,index){
      let canvas = document.getElementById("canvas");
      let x = event.clientX;
      let y = event.clientY;
      if(x > canvas.offsetLeft + 20) {
        this.createNode(index, x - canvas.offsetLeft, y)
      }
    },
    drop(e){
    },
    inputResult(){
      let resultArea = document.getElementsByClassName('el-textarea')[0];
      // console.log(resultArea.scrollHeight);
      resultArea.scrollTop = resultArea.scrollHeight
      // console.log(resultArea);
    },
    commit(){
      // this.result += this.command + '\n'
      this.send("command:"+this.command)
      this.command=''
    },
    webSocketInit() {
      if (typeof (WebSocket) === "undefined") {
        alert("您的浏览器不支持socket")
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.websocketPath)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
        this.socket.onclose = this.close
      }
    },
    open() {
      console.log('webSocket建立成功')
    },
    error() {
      console.log("'webSocket连接错误")
    },

    getMessage (msg) {
      let split = msg.data.split("\n");
      this.prefix = split[split.length - 1]
      this.result += "\n" + msg.data.substr(0, msg.data.length - this.prefix.length - 1)
      // console.log(this.result);
      if(this.autoRunFlag && this.autoRunIndex < this.autoRunCommand.length){
        this.command = this.autoRunCommand[this.autoRunIndex]
        console.log(this.command);
        if(this.command.trim()!='logout' && !this.command.trim().startsWith('login:')){
          this.send(`command:${this.command}`)
        } else {
          console.log(this.command)
          this.send(this.command)
        }
        this.autoRunIndex++;
      }
    },
    send(params) {
      this.socket.send(params)
    },
    close (e) {
      console.log("socket已经关闭")
      console.log(e);
    },
    closeShell(){
      this.send("logout")
      this.result = ''
    },
    managePort(){
      this.autoRunCommand = [];
      this.autoRunCommand.push(`login:${this.selectedNode.additionalVal.telnetIp}`)
      this.autoRunCommand.push('configure terminal')
      this.autoRunCommand.push(`hostname ${this.selectedNode.text}`)
      this.selectedNode.additionalVal.ports.forEach(port => {
        this.autoRunCommand.push(`interface ${port.port}`)
        this.autoRunCommand.push(`ip address ${port.ip} ${port.mask}`)
        this.autoRunCommand.push(`no shut`)
      })
      this.autoRunFlag = true;
      this.autoRunIndex = 1
      this.send(this.autoRunCommand[0]);
    }
  },
  watch:{
    nodeList(val){
      if (val.length == 2){
        let link = new JTopo.CurveLink(val[0], val[1]);
        link.lineWidth = 3; // 线宽
        // link.offsetGap = 35;
        // link.bundleGap = 15; // 线条之间的间隔
        this.scene.add(link)
        this.nodeList = []
      }
    },
    result(){
      this.inputResult()
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  ul {
    list-style-type: none;
  }
  /deep/ .el-dialog__body{
    padding-top: 0px;
  }
  /deep/ .el-textarea__inner{
    background-color: #FFF!important;
    color: black!important;
  }
</style>
